﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Threading;
using System.Xml;
using LockCrypt.Core;

namespace LockCrypt {
    /// <summary>
    /// Miscellaneous WPF utility methods
    /// </summary>
    public partial class WPFUtils {
        /// <summary>
        /// Opens the help file. This avoids messy Windows.Forms usings in every file.
        /// </summary>
        /// <param name="pageName">Name of the page at which to open the help file or <c>null</c> for the contents page.</param>
        public static void OpenHelp(string pageName) {
            if(pageName == null) {
                System.Windows.Forms.Help.ShowHelp(null, "LockCrypt.chm");
            } else {
                System.Windows.Forms.Help.ShowHelp(null, "LockCrypt.chm", System.Windows.Forms.HelpNavigator.Topic, pageName);
            }
        }

        /// <summary>
        /// Walks the tree items to find the node corresponding with the given item, then sets it to be selected.
        /// </summary>
        /// <param name="treeView">The tree view to set the selected item on</param>
        /// <param name="item">The item to be selected</param>
        /// <returns><c>true</c> if the item was found and set to be selected</returns>
        public static bool SetSelectedItem(TreeView treeView, object item) {
            return SetSelected(treeView, treeView, item as INestable);
        }

        private static bool SetSelected(TreeView treeView, ItemsControl parentControl, INestable itemToSelect) {
            if(parentControl == null || itemToSelect == null) {
                return false;
            }
            try {
                foreach(INestable item in parentControl.Items) {
                    TreeViewItem container = parentControl.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
                    if(container == null)
                        continue;
                    if(item.ID == itemToSelect.ID) {
                        // just comparing instances failed
                        container.IsSelected = true;
                        //container.Focus();
                        return true;
                    }
                    container.IsExpanded = true;
                    treeView.UpdateLayout();
                    Lime49.WPF.Utils.WaitForPriority(DispatcherPriority.Background);
                    if(SetSelected(treeView, container, itemToSelect))
                        return true;
                }
            } catch(Exception ex) {
                Console.WriteLine(ex.Message);
            }
            return false;
        }
    }
}
